package com.learn.im.servcie.impl;

import com.alibaba.fastjson.JSON;
import com.learn.im.domain.Chat;
import com.learn.im.enums.MsgType;
import com.learn.im.servcie.ChatService;
import com.learn.im.servcie.MessageHandler;
import com.learn.im.websocket.IMServer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.websocket.Session;

/**
 * @author Emp
 * @version :    1.0
 */
@Service(value = "TEXT")
public class TextMessageHandler implements MessageHandler {

    @Resource
    private ChatService chatService;

    @Override
    public void handle(Chat chat, IMServer fromClient) {
        IMServer toClient = fromClient.client(chat.getTo());
        boolean status = sendTo(toClient.getSession(), JSON.toJSONString(chat));
        chat.setStatus(status);
        chatService.save(chat);
    }

    private boolean sendTo(Session session,String msg){
        if (session == null){
            return false;
        }
        try{
            session.getBasicRemote().sendText(msg);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
}
